#!/bin/bash
set -eu
scriptdir=$(cd $(dirname $0) && pwd)
cd $scriptdir/../..

echo "------> Validating YAML"

doit run generate_optional_yaml_schemas

# Validate adventure files against their schema
#
# We'll go into every directory that has a <xxx>.schema.json file,
# and validate all YAML files in that same directory against the schema file.
#
# The error messages produced by pajv are pretty bad, but we will just
# say that getting an error is better than getting NO error.
#
# If we ever care enough to do something about this, we should be interpreting
# the JSON error outputs of this tool and re-interpreting them with useful
# error messages.

# For magical and mysterious reasons, on GitHub actions using 'npx pajv validate' (which
# would normally be the way to run this command), hangs. It works fine on two of my machines,
# and also in an Ubuntu Docker container, and 'npx pajv help' works as well... but
# 'npx pajv validate' just hangs. Running the 'pajv' binary directly without the use of
# 'npx' does work... so we're just going to ¯\_(ツ)_/¯ and do that.

schemas=$(find content -name \*.schema.json)
echo $schemas
failures=false

for schema in $schemas; do
    # TODO: excluiding cheatsheets for now, while we update the content in them
    if [[ $schema == *"cheatsheets"* ]]; then
        echo "------> Skipping cheatsheet schema $schema"
        continue
    fi
    dir=$(dirname $schema)

    # The non-generated schema files that have required fields. They should be
    # used for 'en.yaml' files. The generated schema files allow all fields to be
    # optional, so they should be used to validate the rest of the yaml files.
    if [[ $schema == *".generated."* ]]; then
        files="*";
        echo "------> Validating with optional fields $(basename $dir)/*.yaml"
    else
        files="en";
        echo "------> Validating with required fields $(basename $dir)/en.yaml"
    fi

    # Run the validator.
    if ! check-jsonschema -o text --schemafile $schema $dir/$files.yaml > validate.txt; then
        cat validate.txt || true
        failures=true
    fi
    rm validate.txt
done

# Also run the structure validator which compares en.yaml to the other languages
echo "------> Checking data completeness w.r.t en.yaml"
python tools/check-yaml-structure.py

if $failures; then
    exit 1
fi
